package renguanyu.app.auth4fx.controller.role;

import javafx.concurrent.Task;
import renguanyu.app.auth4fx.App;
import renguanyu.app.auth4fx.model.role.RoleDto;
import renguanyu.app.auth4fx.service.role.RoleService;
import renguanyu.app.auth4fx.view.role.RoleListView;

import java.util.List;
import java.util.stream.Collectors;

public class RoleInfoDeleteController extends Task<Void> {

    private RoleListView roleListView;
    public RoleInfoDeleteController(RoleListView roleListView) {
        this.roleListView = roleListView;
    }

    public void execute() {
        System.out.println("RoleInfoDelete.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private int affectedRows = 0;
    @Override
    protected Void call() {
        System.out.println("RoleInfoDelete.call");
        RoleDto roleDto = buildRoleDto();
        affectedRows = RoleService.deleteRole(roleDto);
        return null;
    }

    private RoleDto buildRoleDto() {
        List<String> ids = roleListView.selectedRoleList.stream().map(role -> role.getId().toString()).collect(Collectors.toList());
        RoleDto roleDto = new RoleDto();
        roleDto.setIds(ids);
        return roleDto;
    }

    @Override
    protected void running() {
        System.out.println("RoleInfoDelete.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("RoleInfoDelete.succeeded");
        if(affectedRows >= 1){
            App.mainView.setCenter(new RoleListView());
        }
    }

    @Override
    protected void failed() {
        System.out.println("RoleInfoDelete.failed");
    }
}
